﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BSF.BaseService.NScript.Core
{
    /// <summary>
    /// 字符串解析器
    /// 缓存解析结果,加快下次解析
    /// </summary>
    public class StringParser<T>
    {
        private Dictionary<string, T> cache = new Dictionary<string, T>();
        private readonly int recoverCount = 5000;//随机回收限制,未来替换为高性能的LRU

        public void ClearCache()
        {
            lock (this)
            {
                cache.Clear();
            }
        }

        public T Parser(string key, Func<T> func)
        {
            if (cache.ContainsKey(key))
            {
                return cache[key];
            }
            else
            {
                lock (this)
                {
                    if (!cache.ContainsKey(key))
                    {
                        //随机回收一半
                        if (cache.Count > recoverCount)
                        {
                            List<string> recoverKeys = new List<string>(cache.Keys);
                            for (int i = 0; i < recoverCount / 2; i++)
                            {
                                int keyIndex = new Random(new Guid().GetHashCode()).Next(recoverKeys.Count);
                                cache.Remove(recoverKeys[keyIndex]);
                                recoverKeys.RemoveAt(keyIndex);
                            }
                        }

                        T t = func.Invoke();
                        cache.Add(key, t);
                    }
                    return cache[key];
                }
            }
        }
    }
}
